package com.manage.dao;

import com.manage.pojo.Page;
import com.manage.pojo.Profile;
import com.manage.util.ApacheUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.manage.dao
 * @Description:
 * @Date 2022/5/27 14:25
 */
public class ProfileDaoImpl implements ProfileDao {
    private QueryRunner qr = new QueryRunner(ApacheUtil.getDataSource());
    @Override
    public List<Profile> findAllByPage(Page page) {
        String sql = "select * from Profile limit ?, ?";
        List<Profile> list = null;
        try {
            list = qr.query(sql, new BeanListHandler<Profile>(Profile.class), page.getStartRows(), page.getPageSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int findAllPageCount()  {
        String sql = "select count(*) from Profile";
        long count = 0;
        try {
            count = qr.query(sql, new ScalarHandler<Long>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return (int)count;
    }

    @Override
    public Profile findById(int id) {
        String sql = "select * from Profile where id=?";
        Profile profile = null;
        try {
            profile = qr.query(sql, new BeanHandler<Profile>(Profile.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return profile;
    }

    @Override
    public int updateById(Profile profile, int id) {
        String sql = "update Profile set name=?,birthday=?,gender=?,career=?,address=?,mobile=?,picture=? where id =?";
        int count = 0;
        try {
            count = qr.update(sql, profile.getName(), profile.getBirthday(), profile.getGender(), profile.getCareer(),
                    profile.getAddress(), profile.getMobile(),profile.getPicture(),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}
